<style lang="less">
@import './login.less';
</style>

<template>
    <div class="l-wrap" style="width:100%;height:100%;overflow: hidden;">
        <div class="l-container">
            <div class="l-img">
                <div class="l-img-left">
                    <div class="l-img-outline"></div>
                    <div class="l-img-brand"></div>
                    <div class="l-img-outside"></div>
                    <div class="l-img-middle"></div>
                    <div class="l-img-inside"></div>
                </div>
                <div class="l-img-right">
                    <div class="l-img-device-1"></div>
                    <div class="l-img-device-2"></div>
                    <div class="l-img-device-3"></div>
                    <div class="l-img-device-4"></div>
                    <div class="l-img-device-5"></div>
                </div>
            </div>
            <div class="l-login-box" @keydown.enter="handleSubmit">
                <div class="l-login-box-bg"></div>
                <h1 class="l-login-title">
                    云丁智能设备管理系统
                </h1>
                <div class="l-login-form">
                    <Form ref="loginForm" :model="formData" :rules="rules">
                        <FormItem prop="username">
                            <i-input v-model="formData.username" type="text" autofocus placeholder="请输入账号" :maxlength="11" @on-keyup="onKeyup">
                                <span slot="prepend">
                                    <Icon :size="20" type="person"></Icon>
                                </span>
                            </i-input>
                        </FormItem>
                        <FormItem prop="password">
                            <i-input type="password" v-model="formData.password" placeholder="请输入密码" :maxlength="20">
                                <span slot="prepend">
                                    <Icon :size="18" type="locked"></Icon>
                                </span>
                            </i-input>
                        </FormItem>
                        <FormItem>
                            <Button @click="handleSubmit" type="primary" long :loading="loading">
                                <span v-if="!loading">登录</span>
                                <span v-else>登录中...</span>
                            </Button>
                        </FormItem>
                    </Form>
                    <p class="l-login-link">
                        <a :href="environment === 'production' ? 'https://passport.dding.net/search_pass' : 'http://dev-gate.dding.net:7080/search_pass'" target="_blank">
                            找回密码
                        </a>
                    </p>
                    <p class="l-login-link l-login-copyright">
                        Copyright &copy; 2014 - {{curYear}}
                        <br>
                        云丁智能科技（北京）有限公司
                    </p>
                    <p class="l-login-link">
                        <a href="http://www.miibeian.gov.cn/" target="_blank">京ICP备14039007号-2</a>
                    </p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Cookies from 'js-cookie'
import util from '@/libs/util'
import validate from '@/libs/validate'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'
export default {
  data () {
    return {
      environment: process.env.NODE_ENV,
      // noNet: true,
      curYear: new Date().getFullYear(),
      noNet: false,
      loading: false,
      formData: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '请填写手机号码' }, { validator: validate.validPhone }],
        password: { required: true, message: '密码不能为空' }
      }
    }
  },

  computed: {
    isMigrateClient () { // 是2.0分账升级用户
      return this.$store.state.user.isMigrateClient
    }
  },

  methods: {
    onKeyup (e) {
      this.formData.username = this.formData.username.replace(/[^\d]/g, '')
    },

    handleSubmit () {
      try {
        dataCenter.reset()

        this.$refs.loginForm.validate(valid => {
          this.loading = valid
          if (valid) {
            if (this.noNet) {
              this.setPermission()
              return
            }

            let data = {
              name: this.formData.username,
              pass: this.formData.password,
              from: 2
            }

            http.request(this, api.login, null, data, (res, err) => {
              if (res && res.ErrNo !== 0) {
                this.loading = false
                this.$Message.error(res.ErrMsg)
                return
              }
              if (err) {
                this.loading = false
                this.$Message.error(err.data.ErrMsg)
                return
              }
              // 用来刷新其他打开的页面
              localStorage.setItem('last_login_req_id', res && res.ReqID)
              window.last_login_req_id = res && res.ReqID

              http.request(this, api.user_info, null, null, (res, err) => {
                if (err || !res || !res.role || !res.permission_groups || !res.permission_groups.length) {
                  this.loading = false
                  if (err.data && err.data.err_code === 401005) {
                    this.$Message.error(err.data.err_msg)
                  } else {
                    this.$Message.error('没有权限')
                  }
                  return
                }

                this.$Message.success('登录成功')
                this.$store.commit('updateUserInfo', res)
                this.setPermission(res)
              }, true)
            })
          }
        })
      } catch (error) {
        util.log('登录报错', error)
      }
    },

    setPermission (permissions) {
      this.$store.commit('setPermissionList', permissions)
      const username = this.formData.username
      Cookies.set('user', username)
      if (this.isMigrateClient) {
        this.$router.push('/fund/account_information')
      } else {
        // 判断是否曾经登陆过
        this.getLoginStatus(username)
      }
    },
    getLoginStatus (username) {
      // 判断是否曾经登陆过
      let once_logged_in_users = localStorage.once_logged_in_users
      try {
        once_logged_in_users = once_logged_in_users ? JSON.parse(once_logged_in_users) : {}

        if (once_logged_in_users[username]) {
          // 登陆过
          this.$router.push('/home')
        } else {
          // 未登陆过
          once_logged_in_users[username] = 1
          localStorage.setItem('once_logged_in_users', JSON.stringify(once_logged_in_users))
          this.$router.push('/guide/1')
        }
      } catch (error) {
        // JSON.parse出错,判定为未登陆过
        console.log('error', error)
        once_logged_in_users = {}
        once_logged_in_users[username] = 1
        localStorage.setItem('once_logged_in_users', JSON.stringify(once_logged_in_users))
        this.$router.push('/guide/1')
      }
    }
  }
}
</script>

<style>
</style>